<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PAG</title>
    <link rel="icon" href="https://pag.io/img/favicon.png" />
    <style>
      body {
        padding: 12px;
      }
      .header {
        height: 64px;
        border-bottom: 1px solid rgb(193, 193, 193);
        margin-bottom: 24px;
      }
    </style>
  </head>
  <body>
    <div class="header">
      <img src="../assets/logo.png" alt="logo" width="133" height="48" />
    </div>
    <div id="content">
      <canvas class="canvas" id="pag"></canvas>
    </div>
    <script src="https://unpkg.com/libpag@latest/lib/libpag.min.js"></script>
    <script>
      window.onload = async () => {
        const pagUrl = '../assets/snowman.pag';
        const PAG = await window.libpag.PAGInit();
        const fileBlob = await fetch(pagUrl).then((response) => response.blob());
        const file = new window.File([fileBlob], pagUrl.replace(/(.*\/)*([^.]+)/i, '$2'));
        const pagFile = await PAG.PAGFile.load(file);
        document.getElementById('pag').width = await pagFile.width();
        document.getElementById('pag').height = await pagFile.height();
        const pagView = await PAG.PAGView.init(pagFile, '#pag');
        pagView.setRepeatCount(0);
        await pagView.play();
        // Get editable image count.
        const editableImageCount = await pagFile.numImages();
        let editableLayerList = [];
        for (let i = 0; i < editableImageCount; i++) {
          const vectorPagLayer = await pagFile.getLayersByEditableIndex(i, PAG.LayerType.Image);
          for (let j = 0; j < vectorPagLayer.size(); j++) {
            const pagLayerWasm = vectorPagLayer.get(j);
            const pagLayer = new PAG.PAGLayer(pagLayerWasm);
            const startTime = await pagLayer.startTime();
            const duration = await pagLayer.duration();
            editableLayerList.push({ index: i, startTime: startTime, duration: duration });
          }
        }
        // Render editable layer info.
        const box = document.createElement('div');
        box.style.display = 'inline-block';
        box.innerText = 'Editable layer info: ';
        editableLayerList.forEach((layer) => {
          const item = document.createElement('div');
          item.style.marginTop = '24px';
          item.innerText = `index: ${layer.index} startTime: ${layer.startTime} duration: ${layer.duration}`;
          box.appendChild(item);
        });
        document.getElementById('content').appendChild(box);
      };
    </script>
  </body>
</html>
